import axios,{AxiosRequestConfig} from 'axios';
// nprogress 用于请求 loading
import NProgress from  'nprogress'
import 'nprogress/nprogress.css'

//配置基本请求参数
// axios.defaults.baseURL = import.meta.env.VITE_APP_WEB_URL as string;
axios.defaults.timeout = 60000;
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';

//请求拦截器
axios.interceptors.request.use(
  (config):AxiosRequestConfig<any> =>{
    const token = window.sessionStorage.getItem("token");
    if(token){
      // @ts-ignore
      config.headers.token = token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
)

//响应拦截器
axios.interceptors.response.use((res)=>{
  //对相应的数据进行拦截处理
  return res;
  }
)

//相应数据类型
interface ResType<T>{
  code:number
  data?:T
  msg:string
  error?:string
}

//定义请求方法
interface Http{
  get<T>(url:string,param ?:unknown,):Promise<ResType<T>>
  post<T>(url:string,param ?:unknown,):Promise<ResType<T>>
  upload<T>(url:string,param ?:unknown,):Promise<ResType<T>>
  download (url : string):void
}

const http : Http = {
  get(url:string,params ?:unknown){
    return new Promise((resolve,reject)=>{
      NProgress.start()
      axios
        .get(url,{params:params})
        .then((res)=>{
          NProgress.done()
          resolve(res.data);
        })
        .catch((err)=>{
          NProgress.done()
          reject(err);
      })
    })
  },
  post(url:string,params ?:unknown){
    return new Promise((resolve,reject)=>{
      NProgress.start()
      axios
        .post(url,JSON.stringify(params))
        .then((res)=>{
          NProgress.done()
          resolve(res.data);
        })
        .catch((err)=>{
          NProgress.done()
          reject(err);
      })
    })
  },
  //上传文件
  upload(url:string,file){
    return new Promise((resolve,reject)=>{
      NProgress.start()
      axios
        .post(url,file,{
          headers:{
            'Content-Type':'multipart/form-data'
          }
        })
        .then((res)=>{
          NProgress.done()
          resolve(res.data);
        })
        .catch((err)=>{
          NProgress.done()
          reject(err);
      })
    })
  },
  //下载?看不懂
  download (url : string):void{
    const  iframe = document.getElementById('iframe') as HTMLIFrameElement;
    iframe.style.display = 'none'
    iframe.src = url;
    iframe.onload = () => {
      document.body.removeChild(iframe)
    }
    document.body.appendChild(iframe)
  }
}

export default http;
